<?php
namespace App\Http\Middleware;


use App\Exception\IPException;
use App\Helper\IPBlackListHelper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Bean\BeanFactory;
use Swoft\Console\Router\Module;
use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Contract\MiddlewareInterface;

/**
 * 黑名单检测
 * Class BlackListMiddleware
 * @package App\Http\Middleware
 * @Bean("BlackListMiddleware")
 */
class BlackListMiddleware implements MiddlewareInterface
{

    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 检测模块启用状态
        if (! constant(Module::DEFINE_DISABLE_BLACK_LIST)) {
            // 开启 IP 黑名单
            $IP = ip();

            /** @var IPBlackListHelper $IPBlackListHelper */
            $IPBlackListHelper = BeanFactory::getBean("IPBlackList");
            if ($IPBlackListHelper->inBlack($IP)) {
                // 在黑名单  抛出异常
                throw new IPException();
            }
        }

        return $handler->handle($request);
    }
}
